﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SmartCity.BasicData.Api.Application.Commond.Area;
using SmartCity.BasicData.Common;
using SmartCity.BasicData.Common.Menus;
using SmartCity.BasicData.Domain;
using SmartCity.BasicData.Repo;
using System.Collections.Generic;

namespace SmartCity.BasicData.Api.Application.Handler.Area
{
    /// <summary>
    /// 获取所有区域的树形数据结构
    /// </summary>
    public class GetAreaHandler : IRequestHandler<GetAreaCommand, ApiResult<IList<AreaDTO>>>
    {
        private readonly IBaseRepository<AreasModel> areaRepo;
        private readonly IMapper mapper;

        public GetAreaHandler(IBaseRepository<AreasModel> areaRepo, IMapper mapper)
        {
            this.areaRepo = areaRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<IList<AreaDTO>>> Handle(GetAreaCommand request, CancellationToken cancellationToken)
        {
            //1.实例化一个ApiResult ,用来保存响应结果
            ApiResult<IList<AreaDTO>> result = new ApiResult<IList<AreaDTO>>();

            result.Code = EnumResultCode.Success;
            result.Msg = "获取区域树结构成功!";
            result.Data = GetAreasTree(0);

            return Task.FromResult(result);
        }
        //递归获取所有区域的树结构
        private IList<AreaDTO> GetAreasTree(long parentId)
        {
            var areas = areaRepo.GetAsync(x => x.ParentId == parentId).Result;
            var dtos = mapper.Map<List<AreaDTO>>(areas);
            dtos.ForEach(d =>
            {
                d.Children = GetAreasTree(d.Id);
            });
            return dtos;
        }

        //private IList<AreaDTO> GetAreaTree(long parentId = 0)
        //{
        //    var areas = areaRepo.GetAsync(x => x.ParentId == parentId).Result;
        //    IList<AreaDTO> areaDtos = new List<AreaDTO>();
        //    foreach (var item in areas)
        //    {
        //        AreaDTO dto = new AreaDTO();
        //        dto.Id = item.Id;
        //        dto.AreaName = item.AreaName;
        //        dto.Children = GetAreaTree(item.Id);

        //        areaDtos.Add(dto);
        //    }
        //    return areaDtos;
        //}


        private IList<AreaDTO> GetAreaTree(long parentId =0) {
            var areas = areaRepo.GetAsync(x => x.ParentId == parentId).Result;
            var aredtos = mapper.Map<IList<AreaDTO>>(areas);
            foreach (var item in aredtos)
            {
                item.Children = GetAreaTree(item.Id);
            }
            return aredtos;

        }
    }
}
